<template>
  <div>
    <van-nav-bar title="扫码" left-text="返回" left-arrow @click-left="onClickLeft" />
  </div>

  <!-- 全屏黑色背景 -->
  <div class="scan-background">
    <div class="scan-box">
      <div class="scan-frame">
        <!-- 视频元素用于显示相机画面 -->
        <video ref="video" class="video" autoplay></video>
        <div class="scan-bar"></div>
      </div>
    </div>

    <!-- 扫码完成按钮 -->
    <div class="button-container">
      <van-button round type="success" size="small" @click="goCharging">扫码完成</van-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import router from '@/router';
import jsQR from 'jsqr'; // 引入 jsQR 库，用于二维码解析

const videoRef = ref(null);

const onClickLeft = () => {
  history.back();
};

const goCharging = () => {
  console.info('去充电');
  router.push('/charging/start');
};

// 获取视频流并开始扫描
const startScanner = async () => {
  try {
    // 获取设备的相机
    const stream = await navigator.mediaDevices.getUserMedia({
      video: { facingMode: 'environment' }, // 后置摄像头
    });

    // 将视频流绑定到 video 元素
    videoRef.value.srcObject = stream;

    // 开始扫描二维码
    scanQRCode(stream);
  } catch (error) {
    console.error('无法访问摄像头:', error);
  }
};

// 扫描二维码并处理识别结果
const scanQRCode = (stream) => {
  const videoElement = videoRef.value;

  // 创建一个 canvas 用于二维码解析
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');

  const tick = () => {
    if (videoElement && videoElement.readyState === videoElement.HAVE_ENOUGH_DATA) {
      canvas.width = videoElement.videoWidth;
      canvas.height = videoElement.videoHeight;

      // 将视频帧绘制到 canvas 上
      ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height);

      // 扫描二维码
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      const code = jsQR(imageData.data, canvas.width, canvas.height, {
        inversionAttempts: 'dontInvert',
      });

      // 如果识别到二维码
      if (code) {
        console.log('二维码扫描结果:', code.data);
        alert('二维码扫描成功: ' + code.data);
        // 在这里可以执行扫码后的逻辑，如跳转页面等
        goCharging();
      }
    }
    requestAnimationFrame(tick);
  };

  tick(); // 启动扫码循环
};

onMounted(() => {
  startScanner(); // 组件挂载时开始扫描
});
</script>

<style scoped>
/* 全屏黑色背景 */
.scan-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7); /* 半透明黑色背景 */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
}

/* 扫码框 */
.scan-box {
  position: relative;
  width: 80%;
  height: 60%;
  border: 2px solid #08c; /* 扫码框颜色 */
  border-radius: 10px;
  overflow: hidden;
}

/* 扫码框内的虚线框 */
.scan-frame {
  position: absolute;
  top: 10%;
  left: 10%;
  right: 10%;
  bottom: 10%;
  border: 2px dashed #08c;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
  height: 100%;
  width: 100%;
}

/* 视频元素 */
.video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 扫码条 */
.scan-bar {
  position: absolute;
  width: 100%;
  height: 4px;
  background-color: rgba(8, 204, 255, 0.8); /* 扫码条颜色 */
  animation: scanMove 2s infinite linear;
}

/* 扫描条的动画效果 */
@keyframes scanMove {
  0% {
    top: -5%;
  }
  50% {
    top: 90%;
  }
  100% {
    top: -5%;
  }
}

/* 扫码完成按钮 */
.button-container {
  position: absolute;
  bottom: 20px;
  width: 100%;
  text-align: center;
}
</style>
